<template>
    <div class="hkconnect-card">
        <div class="card-header">
            <h3>沪深港通资金流</h3>
        </div>
        <div class="card-body">
            <div ref="chartRef" class="chart-container"></div>
            <div class="net-funds">
                <div class="fund-label">成交净买额</div>
                <div
                    class="fund-item"
                    :class="{
                        positive: netBuyAmountNorth > 0,
                        negative: netBuyAmountNorth < 0,
                    }"
                >
                    <div class="fund-value">
                        {{ formatFunds(netBuyAmountNorth) }}亿元
                    </div>
                </div>
                <div
                    class="fund-item"
                    :class="{
                        positive: netBuyAmountSouth > 0,
                        negative: netBuyAmountSouth < 0,
                    }"
                >
                    <div class="fund-value">
                        {{ formatFunds(netBuyAmountSouth) }}亿元
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
  
  <script setup>
    import { ref, onMounted, onBeforeUnmount, inject } from 'vue';
    import * as echarts from 'echarts/core';
    import { BarChart } from 'echarts/charts';
    import {
        TitleComponent,
        TooltipComponent,
        GridComponent,
        LegendComponent,
    } from 'echarts/components';
    import { CanvasRenderer } from 'echarts/renderers';
    import { getHsgtFundFlow } from '../api/api.js';

    // 导入暂停更新状态
    const shouldPauseUpdates = inject('shouldPauseUpdates', ref(false));

    echarts.use([
        TitleComponent,
        TooltipComponent,
        GridComponent,
        LegendComponent,
        BarChart,
        CanvasRenderer,
    ]);

    const chartRef = ref(null);
    const netBuyAmountNorth = ref(0);
    const netBuyAmountSouth = ref(0);
    const totalTurnoverNorth = ref(0);
    const totalTurnoverSouth = ref(0);
    const boardNames = ref(['港股通（沪）', '港股通（深）']);

    let chart = null;
    let dataRefreshTimer = null; // 添加数据刷新定时器变量

    // 增加定时数据刷新功能
    const fetchDataWithCheck = () => {
        // 只有在不暂停更新时才获取数据
        if (!shouldPauseUpdates.value) {
            fetchStockConnectData();
        } else {
            console.log('沪深港通数据更新已暂停');
        }
    };

    const formatFunds = value => value.toFixed(2);

    /**
     * 更新图表数据
     * 当数据变化时，更新已初始化的ECharts图表
     */
    const updateChart = () => {
        // 检查图表实例是否存在，不存在则退出
        if (!chart) return;

        // 只更新需要变化的配置项，提高性能
        chart.setOption({
            xAxis: [
                {
                    // 更新X轴类别数据（沪深港通板块名称）
                    data: boardNames.value,
                },
            ],
            series: [
                {
                    name: '成交额',
                    // 更新图表数据系列，对应北向和南向资金成交额
                    data: [totalTurnoverNorth.value, totalTurnoverSouth.value],
                },
            ],
        });
    };

    /**
     * 初始化ECharts图表
     * 创建图表实例并设置基础配置
     */
    const initChart = () => {
        // 确保DOM元素已挂载
        if (!chartRef.value) return;

        // 如果已有图表实例，先销毁以防内存泄漏
        if (chart) chart.dispose();

        // 创建新的图表实例
        chart = echarts.init(chartRef.value);

        // 配置图表选项
        const option = {
            // 提示框配置
            tooltip: {
                trigger: 'axis', // 坐标轴触发提示
                axisPointer: { type: 'shadow' }, // 阴影指示器
            },
            // 图表网格配置，控制图表位置和大小
            grid: {
                top: '15%',
                left: '10%',
                right: '10%',
                bottom: '0%',
                containLabel: true, // 包含坐标轴标签
            },
            // X轴配置
            xAxis: [
                {
                    type: 'category', // 类别轴
                    data: boardNames.value, // 板块名称数据
                    // 自定义坐标轴样式，符合深色主题
                    axisLine: { lineStyle: { color: '#8cd6ff' } },
                    axisLabel: { color: '#a7cbf4', fontSize: 15 }, // 轴标签样式
                },
            ],
            // Y轴配置
            yAxis: [
                {
                    type: 'value', // 数值轴
                    name: '(亿元)', // 单位标注
                    nameTextStyle: { color: '#9da1b7' }, // 单位文字样式
                    axisLine: { lineStyle: { color: '#8cd6ff' } }, // 轴线样式
                    axisLabel: { color: '#9da1b7', fontSize: 12 }, // 轴标签样式
                    // 分割线样式，淡化以不干扰数据展示
                    splitLine: { lineStyle: { color: 'rgba(140, 214, 255, 0.2)' } },
                },
            ],
            // 数据系列配置
            series: [
                {
                    name: '成交额',
                    type: 'bar', // 柱状图
                    barWidth: '13%', // 柱宽
                    // 北向和南向资金成交额数据
                    data: [totalTurnoverNorth.value, totalTurnoverSouth.value],
                    // 柱形图样式
                    itemStyle: { color: '#4a9ff5' }, // 柱体颜色
                },
            ],
        };

        // 应用配置到图表
        chart.setOption(option);
    };

    /**
     * 处理窗口大小变化事件
     * 确保图表自适应调整大小
     */
    const handleResize = () => {
        if (chart) chart.resize();
    };

    const fetchStockConnectData = async () => {
        try {
            const res = await getHsgtFundFlow();
            if (res.code === '200' && Array.isArray(res.data)) {
                const [north, south] = res.data;

                // 更新响应式数据
                netBuyAmountNorth.value = north?.netBuyAmount || 0;
                totalTurnoverNorth.value = north?.totalTurnover || 0;

                netBuyAmountSouth.value = south?.netBuyAmount || 0;
                totalTurnoverSouth.value = south?.totalTurnover || 0;

                boardNames.value = [north.boardName, south.boardName];

                updateChart();
            }
        } catch (error) {
            console.error('获取沪深港通数据失败:', error);
        }
    };

    onMounted(() => {
        initChart();
        fetchStockConnectData();

        // 添加定期刷新数据
        dataRefreshTimer = setInterval(() => {
            fetchDataWithCheck();
        }, 30000); // 每30秒刷新一次数据

        window.addEventListener('resize', handleResize);
    });

    onBeforeUnmount(() => {
        if (chart) {
            chart.dispose();
            chart = null;
        }

        // 清除定时器
        if (dataRefreshTimer) {
            clearInterval(dataRefreshTimer);
            dataRefreshTimer = null;
        }

        window.removeEventListener('resize', handleResize);
    });
</script>
  
  <style scoped>
    @import '../assets/css/style.css';

    .hkconnect-card {
        background-color: #001e4a;
        border-radius: 5px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        height: 100%;
    }

    .chart-container {
        width: 100%;
        height: 250px;
    }

    .net-funds {
        display: flex;
        justify-content: space-around;
        margin-right: 10%;
        margin-top: 15px;
    }

    .fund-item {
        text-align: center;
        padding: 5px;
        border-radius: 5px;
        background-color: #062052;
        width: 45%;
    }

    .fund-label {
        font-size: 15px;
        width: 15%;
        margin-bottom: 5px;
        text-align: center;
        padding: 5px;
        border-radius: 5px;
        color: #9bddff;
        background-color: #062052;
    }

    .fund-value {
        font-size: 17px;
        font-weight: bold;
    }

    .positive .fund-value {
        color: #f56c6c;
    }

    .negative .fund-value {
        color: #2589ff;
    }

    @media (min-height: 1200px) {
        .chart-container {
            height: 300px;
        }

        .fund-value {
            font-size: 20px;
        }
    }

    @media (min-height: 1800px) {
        .chart-container {
            height: 350px;
        }

        .fund-value {
            font-size: 24px;
        }

        .fund-label {
            font-size: 18px;
        }
    }
</style>
